<template>
  <!-- <h1>我是角色管理页面</h1> -->
  <!-- 添加角色功能 -->
  <el-button type="primary" @click="addRoleHandle" style="margin: 20px">添加角色</el-button>
  <!-- 展示已有角色（修改角色权限） -->
  <!-- <div>{{ roleList }}</div> -->
  <el-table :data="roleList">
    <el-table-column type="index" label="索引" width="100"></el-table-column>
    <el-table-column prop="name" label="角色名称"></el-table-column>
    <el-table-column prop="create_time" label="创建时间">
      <template #default="scope">
        {{ showTime(scope.row.create_time) }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <!-- 执行修改权限操作 -->
      <template #default="scope">
        <el-button size="small" @click="editPermHandler(scope.row)">
          编辑权限
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加角色的弹窗 -->
  <el-dialog v-model="addDialogRef" title="添加角色" width="400" @close="closeAddRole">
    <!-- 表单 -->
    <el-form :model="role" :rules="roleRules" ref="addRoleEle">
      <el-form-item label="角色名称：" prop="rolename">
        <el-input v-model="role.rolename"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addRole"> 确定 </el-button>
        <el-button @click="closeAddRole">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改角色权限的弹窗 -->
  <el-dialog title="修改权限" v-model="editPermRef" @close="closePermHandler">
    <!-- label, children需要配置字段，放到props属性上 -->
    <el-tree v-if="editPermRef" ref="permTreeEle" :data="permissions" :props="defaultProps" show-checkbox
      :default-expanded-keys="['4']" :default-checked-keys="menusRef" node-key="index"></el-tree>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="updatePerm"> 确定 </el-button>
        <el-button @click="closePermHandler">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reqAddRole, reqGetRoles, reqUpdateRoles } from "@/api/reqRole"
import type { ROLE } from "@/types/role"
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type TreeInstance,
} from "element-plus"
import { showTime } from "@/util/tools"
import { onMounted, reactive, ref } from "vue"
import { permissions } from "@/config/permission"
import { useUserStore } from "@/store/useUserStore"
import { useRoleStore } from "@/store/useRoleStore"
import { storeToRefs } from "pinia"
const store = useUserStore()
const roleStore = useRoleStore()
const { roleList } = storeToRefs(roleStore)
const { getRoles } = roleStore

// 添加角色
const addRoleEle = ref<FormInstance>()
const addDialogRef = ref(false)
const addRoleHandle = function () {
  addDialogRef.value = true
}
const role = reactive({
  rolename: "",
})
// 添加校验规则
const roleRules = reactive<FormRules<typeof role>>({
  rolename: [
    {
      // 只有一个，角色名称只能为汉字
      pattern: /^[\u4e00-\u9fa5]+$/,
      message: "角色名称只能由汉字构成",
      trigger: "change",
    },
    {
      required: true,
      message: "请写入角色名称",
      trigger: "blur",
    },
  ],
})
// 定义确定添加的函数
const addRole = function () {
  // 表单验证
  if (addRoleEle.value) {
    addRoleEle.value.validate(async (isOk) => {
      if (isOk) {
        // 发送添加角色的请求
        const { status, msg } = await reqAddRole({ name: role.rolename })
        if (status === 0) {
          ElMessage({
            type: "success",
            message: "添加成功",
          })
          closeAddRole()
          // 重新获取一下所有的角色
          getRoles()
        }
      }
    })
  }
}

const closeAddRole = function () {
  if (addRoleEle.value) {
    addRoleEle.value.resetFields()
    addDialogRef.value = false
  }
}


// 修改权限
const editPermRef = ref(false)
const permTreeEle = ref<TreeInstance>()
const defaultProps = {
  label: "title",
  children: "children",
  disabled: "disabled",
}
// 记录当前的menus 作为默认选中的值
const menusRef = ref<string[]>(["/user", "/role", "/major"])
let roleId: string = ""
const editPermHandler = function (row: ROLE) {
  menusRef.value = row.menus
  roleId = row._id
  editPermRef.value = true
  //
}
const closePermHandler = function () {
  editPermRef.value = false
  menusRef.value = []
}
const updatePerm = async function () {
  // 1. 拿到我选中后的menus
  let menus = permTreeEle.value?.getCheckedKeys() || []
  menus = menus.filter((value) => value !== "4")
  // console.log(menus)
  await reqUpdateRoles({
    _id: roleId,
    menus: menus as string[],
    auth_name: store.user.name,
  })
  ElMessage.success("修改权限成功")
  // 关闭弹窗
  closePermHandler()
  // 重新获取所有角色信息
  getRoles()
}


</script>

<style></style>
